﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Ace;
using Ace.Application.Common;
using Ace.Application.Wiki;
using Ace.Entity.Wiki;
using Ace.IdStrategy;
using Ace.Web.Mvc;
using Ace.Web.Mvc.Authorization;
using Ace.Web.Mvc.Models;
using Chloe.Admin.Common;
using Chloe.Admin.Common.Tree;
using Microsoft.AspNetCore.Mvc;
using NLog;
using Senparc.Weixin.TenPay.V3;

namespace Chloe.Admin.Areas.Wiki.Controllers
{

    [Area(AreaNames.Wiki)]
    [Permission("wiki.refund")]
    public class RefundController : WebController<IRefundService>
    {
        public IActionResult Index()
        {
            
            return View();
        }

        public ActionResult Models(Pagination pagination,int ST=-1,int SortID=-1, string keyword="")
        {
            
            PagedData<RefundInfo> pagedData = this.Service.GetPageData(pagination, ST, SortID, keyword);
            return this.SuccessData(pagedData);
        }


        [Permission("wiki.refund.delete")]
        [HttpPost]
        public ActionResult Delete(string id)
        { 
            this.Service.Delete(id);
            return this.SuccessMsg("删除成功");
        }

       
        [Permission("wiki.refund.edit")]
        [HttpPost]
        public ActionResult Edit(UpdateRefundInput modle)
        {
            Logger logger = LogManager.GetLogger("SimpleDemo");
            if(modle.ST==1)
            {
                if (modle.out_refund_status == "0" && modle.out_refund_no == "0")
                {

                    ShopOrder order = this.CreateService<IShopOrderService>().GetModel(modle.OrderID);
                    if (!string.IsNullOrEmpty(order.transaction_id) && !string.IsNullOrEmpty(order.OrderCode))
                    {
                        string TenPayV3_Key = Globals.Configuration["AppSettings:TenPayV3_Key"].ToString();
                        string mch_id = Globals.Configuration["AppSettings:TenPayV3_MchId"].ToString();
                        string appid = Globals.Configuration["AppSettings:WxOpenAppId"].ToString();
                        string nonce_str = TenPayV3Util.GetNoncestr();
                        string transaction_id = order.transaction_id;
                        string out_trade_no = order.OrderCode;
                        string out_refund_no = IdHelper.CreateStringSnowflakeId();
                        int total_fee = Convert.ToInt32(order.Total * 100);
                        int refund_fee = Convert.ToInt32(modle.RefundPrice * 100);

                        string notify_url = Globals.Configuration["AppSettings:FileDomain"].ToString() + "/API/ReFundNotify";

                        var dataInfo = new TenPayV3RefundRequestData(appid, mch_id, TenPayV3_Key,
                        null, nonce_str, null, out_trade_no, out_refund_no, total_fee, refund_fee, mch_id, null, notifyUrl: notify_url);
                        var cert = @"D:\cert\apiclient_cert.p12";//根据自己的证书位置修改
                        var password = mch_id;//默认为商户号，建议修改
                        var result = TenPayV3.Refund(dataInfo, cert, password);
                        //return Content(string.Format("退款结果：{0} {1}。您可以刷新当前页面查看最新结果。", result.result_code, result.err_code_des));
                        if (result.result_code == "SUCCESS")
                        {
                            this.CreateService<IShopOrderService>().UpdateReFundStatu(order.OrderCode, out_refund_no, "");
                            //return this.SuccessMsg("退款申请已提交");
                            logger.Info("退款申请已提交");

                            modle.out_refund_no = out_refund_no;
                            modle.out_refund_status = "";
                            this.Service.Update(modle);
                            return this.SuccessMsg("退款申请已提交");
                        }
                        else
                        {
                            logger.Info(result.err_code + "," + result.err_code_des);
                            return this.FailedMsg(result.err_code + "," + result.err_code_des);
                        }
                    }
                    else if(!string.IsNullOrEmpty(order.ChargeID) && !string.IsNullOrEmpty(order.ChargeCode))
                    {
                        UsersCharge charge = this.CreateService<IUsersChargeService>().GetModel(order.ChargeID);
                        if(charge!=null)
                        {
                            //生成余额支付记录
                            string ChargeCode = "WH" + DateTime.Now.ToString("yyyyMMddHHmmssfff");
                            AddUsersChargeInput input = new AddUsersChargeInput();
                            input.Balance = 0;
                            input.ChargeCode = ChargeCode;
                            input.ChargeSort = 1;// 消费0 1充值
                            input.Title = "退款";
                            input.ChargeTotal = charge.ChargeTotal;
                            input.CreateDate = DateTime.Now;
                            input.CreateID = this.CurrentSession.UserId;
                            input.ImageUrl = "";
                            input.UserID = modle.UserID;
                            UsersCharge NewCharge = this.CreateService<IUsersChargeService>().Add(input);


                            this.CreateService<IShopOrderService>().UpdateReFundStatu(order.OrderCode, ChargeCode, "SUCCESS");
                            modle.out_refund_no = ChargeCode;
                            modle.out_refund_status = "SUCCESS";
                            this.Service.Update(modle);

                            return this.SuccessMsg("余额退款成功");
                        }
                        else
                        {
                            return this.SuccessMsg("余额退款异常");
                        }
                    }
                    else
                    {
                        logger.Info("未付款订单");
                        return this.FailedMsg("未付款订单");
                    }
                }
                else
                {
                    this.Service.Update(modle);
                    return this.FailedMsg("不能重复退款");
                }
            }
            else
            {
                return this.SuccessMsg();
            }

            
            
        }

        [Permission("wiki.refund.add")]
        [HttpPost]
        public ActionResult Add(AddRefundInput modle)
        { 
            this.Service.Add(modle);
            return this.SuccessMsg("添加成功");
        }

    }
}